package cn.group.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 *   文件上传
 *
 *
 */

@Api(tags = "文件操作接口")
@Controller
public class FileController {
    @ApiOperation("文件上传")
    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(@ApiParam(value = "文件") MultipartFile file, HttpServletResponse response, HttpServletRequest req) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件上传失败");
        }
        //获得文件地址
        String baseDir = req.getServletContext().getRealPath("/WEB-INF/file");
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        //获取时间
        String dateStr = dateFormat.format(new Date());
        //目录地址  File.separator-->文件中的分隔符
        String dir = baseDir + File.separator + dateStr;
        //判断目录是否存在
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            //创建目录
            dirFile.mkdirs();
        }

        //在当前文件下存文件并保证文件名不重复
        //获取文件名的后缀，分割 file.getOriginalFilename()-->原文件名
        String oldFileName = file.getOriginalFilename();
        //分割,拿到文件后缀
        String fileSuffix = oldFileName.substring(oldFileName.lastIndexOf("."), oldFileName.length());
        //获取时间戳，进行拼接-->得到文件名
        String fileName = System.currentTimeMillis() + fileSuffix;
        //文件保存的地址 = 目录地址 + 分割符 + 文件名
        String path = dir + File.separator + fileName;
        System.out.println(path);
        String urlSql = path.substring(path.lastIndexOf("file\\"));

        System.out.println(urlSql);

        //保存文件
        try {
            //transferTo --> 传输
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return urlSql;
    }
}
